package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"shopping-mall/models"
	"shopping-mall/shopping_rpc/internal/svc"
	"shopping-mall/shopping_rpc/shopping_rpc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type HotTopLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHotTopLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HotTopLogic {
	return &HotTopLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HotTopLogic) HotTop(in *shopping_rpc.HotTopRequest) (*shopping_rpc.HotTopResponse, error) {
	// todo: add your logic here and delete this line
	var products []struct {
		models.Product
		ClassName string
		UserName  string
	}
	var data []*shopping_rpc.FromProductList
	key := fmt.Sprintf("hot")
	get, _ := models.RDB.Get(models.Ctx, key).Result()
	if get == "" {
		if models.DB.Model(&models.Product{}).Joins("join users on products.user_id = users.id join classes on products.class_id = classes.id").Order("browse_number desc").Limit(20).Select("products.*,classes.name as class_name,users.name as user_name").Scan(&products).Error != nil {
			return nil, fmt.Errorf("服务器繁忙")
		}
		for _, product := range products {
			get := shopping_rpc.FromProductList{
				UserName:     product.UserName,
				Title:        product.Title,
				Price:        float32(product.Price),
				BrowseNumber: int64(product.BrowseNumber),
				Image:        product.Image,
				ClassName:    product.ClassName,
			}
			data = append(data, &get)
		}
		set, _ := json.Marshal(&data)
		models.RDB.Set(models.Ctx, key, set, 24*time.Hour)
	} else {
		json.Unmarshal([]byte(get), &data)
	}
	return &shopping_rpc.HotTopResponse{
		Products: data,
	}, nil
}
